package com.llf.Blog.Controller;



import com.llf.Blog.Pojo.Blog;
import com.llf.Blog.Pojo.Comment;
import com.llf.Blog.Pojo.User;
import com.llf.Blog.Service.BlogService;
import com.llf.Blog.Service.CommentService;
import com.llf.Blog.ServiceImpl.BlogServiceImpl;
import com.llf.Blog.ServiceImpl.CommentServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author llf
 * @since 2021-08-07
 */
@Controller
@Api(value = "提供获取评论信息接口",tags = "评论管理")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    private  String avatar="/images/aoavatar.png";

    /**
     * 根据传递的博客id 查询到博客对应的评论内容
     * @param blogId
     * @param model
     * @return
     */
    @ApiOperation("博客评论查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "long",name = "id", value = "博客ID",required = true)
    })
    @RequestMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId") Long blogId, Model model){
        List<Comment> list = commentService.getCommentByBlogID(blogId);
        Blog blog = blogService.getBlogById(blogId);
        model.addAttribute("comments",list);
        model.addAttribute("authorId",blog.getUserId());
        return "blog :: commentList";
    }

    /**
     *  通过异步请求 来将评论内容持久化
     * @param comment 评论的Comment对象
     * @return
     */
    @ApiOperation("博客评论新增接口")
    @PostMapping("/comments")
    public String toComments( Comment comment, HttpSession session){
        //得到id 作为参数 传给查询请求
        Long id= comment.getBlogId();
        Blog blog = blogService.getBlogById(id);
        //将博客与评论绑定
        comment.setBlog(blog);
        User user = (User) session.getAttribute("user");
        //如果用户登录 就用用户的图像 如果用户没有登录 就使用统一的头像
        if (user.getRole().equalsIgnoreCase("admin")){
            comment.setAdminComment(true);
            comment.setAvatar(user.getAvatar());
        }else {
            comment.setAdminComment(false);
            comment.setAvatar(user.getAvatar());
        }
       if (user.getId().equals(blog.getUserId())){
            comment.setAuthor(true);
        }else {
            comment.setAuthor(false);
        }
        //持久化comment
        commentService.insertComment(comment);
        return "redirect:/comments/" + id;
    }




}
